package com.todod.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.todod.common.util.MinIoUtils;
import com.todod.common.util.Result;
import com.todod.dto.ProjectFileDto;
import com.todod.entity.QueryProjectFile;
import com.todod.entity.ResultData;
import com.todod.mapper.ProjectFileMapper;
import com.todod.model.ProjectFile;
import com.todod.model.ProjectFileEvaluate;
import com.todod.model.User;
import com.todod.service.IUserService;
import com.todod.service.ProjectFileEvaluateService;
import com.todod.service.ProjectFileRecordsService;
import com.todod.service.ProjectFileService;

/**
 * @param
 * @author dyl
 * @date 2021-03-16
 */
@RestController
@RequestMapping("/projectFile")
public class ProjectFileController extends BaseManageController {
	@Autowired
	private ProjectFileService projectFileService;
	@Autowired
	private ProjectFileMapper projectFileMapper;
	@Autowired
	private IUserService iUserService;
	@Autowired
	public ProjectFileEvaluateService projectFileEvaluateService;
	@Value("${file.visit}")
	private String visi;
	// 存储桶名称
	@Value("${minio.bucketName}")
	private String bucketName;
	@Autowired
	private MinIoUtils minIoUtils;

	Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	public ProjectFileRecordsService projectFileRecordsService;

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getListPage")
	public ResultData getListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryProjectFile queryProjectFile) {

		IPage<ProjectFileDto> page = projectFileService.getListPage(_userId, queryProjectFile);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param _userId
	 * @param request
	 * @param response
	 * @param xftId
	 * @param xiangmuId
	 * @param companyId
	 * @return
	 */
	@PostMapping("/uploadFile")
	public ResultData uploadFile(@RequestAttribute Long _userId, HttpServletRequest request,
			HttpServletResponse response, Long xftId, Long xiangmuId, String batchCode) {
		try {
			request.setCharacterEncoding("utf-8");
			User user = iUserService.getById(_userId);

			MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = req.getFile("uploadfile_ant");// 返回上传文件的内容和描述
			String originalName = uploadFile.getOriginalFilename();

			boolean flag2 = projectFileRecordsService.getTimeComparison(_userId, xftId, originalName);
			if (flag2 != true) {
				return ResultData.error("当前系统中的文档已被其他人更新过，是否仍进行上传？");
			} else {
				ProjectFile projectFile = projectFileService.saveUploadFile(_userId, request, xftId, xiangmuId,
						user.getDepartid(), batchCode);
				return ResultData.success("ok", projectFile);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("error");
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/save")
	public ResultData saveData(@RequestAttribute Long _userId, @RequestBody ProjectFile projectFile) {

		projectFileService.saveData(_userId, projectFile);
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/edit")
	public ResultData editData(@RequestAttribute Long _userId, @RequestBody ProjectFile projectFile) {

		projectFileService.editData(_userId, projectFile);
		return ResultData.success();
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getInfo")
	public ResultData getInfo(Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		List<ProjectFileDto> list = projectFileMapper.getInfo(code);
		for (ProjectFileDto key : list) {
			key.setName(key.getOriginalName());
//			key.setUrl(visi + key.getRelativePath());
			if (key.getSuffix().equalsIgnoreCase("docx") || key.getSuffix().equalsIgnoreCase("doc")) {
				key.setUrl(key.getYulanPath());
			} else {
				key.setUrl(key.getAbstractPath());
			}
		}
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getFileInfo")
	public ResultData getFileInfo(Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}

		ArrayList<Object> list = new ArrayList<>();
		List<ProjectFileDto> keys = projectFileMapper.getInfo(code);
		for (ProjectFileDto key : keys) {
//			list.add(visi + key.getRelativePath());
			list.add(key.getAbstractPath());
		}
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param batchCode
	 * @return
	 */
	@GetMapping("/getHistory")
	public ResultData getHistory(String batchCode) {

		List<ProjectFileDto> list = projectFileMapper.getListByBatchCode(batchCode);
		for (ProjectFileDto projectFile : list) {
			User user = iUserService.getById(projectFile.getCreateuserId());
			projectFile.setCreateuserName(user.getNickName());
		}

		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getFileList")
	public ResultData getFileList(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);

		List<ProjectFileDto> list = projectFileMapper.getFileList(_userId, user.getDepartid());
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectInfo
	 * @return
	 */
	@RequestMapping("/getSPListPage")
	public ResultData getSPListPage(@RequestAttribute Long _userId, HttpServletRequest request,
			@RequestBody QueryProjectFile queryProjectFile) {

		IPage<ProjectFileDto> page = projectFileService.getSPListPage(_userId, queryProjectFile);
		return ResultData.success("ok", page);
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delete")
	public ResultData delete(@RequestAttribute Long _userId, Long code) {

		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}
		List<ProjectFileEvaluate> list = projectFileEvaluateService.getEvaluateListByFileId(code);

		ProjectFile projectFile = projectFileMapper.selectById(code);
		if (!_userId.equals(projectFile.getCreateuserId())) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "不可删除非当前登录人创建的文档");
		}
		if (projectFile.getState().equalsIgnoreCase("2")) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "不可删除审批通过的文档");
		}
		if (list != null && list.size() > 0) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "当前文档已评价，不可删除");
		}
		projectFileMapper.deleteById(code);
		minIoUtils.removeObject(bucketName, projectFile.getFileName());
		return ResultData.success();
	}

	/**
	 * @Title: downLoad
	 * @Description: 附件下载
	 * @author lql
	 * @date 2021年3月1日
	 * @return ResponseEntity响应的头文件信息，具体信息
	 */
	@RequestMapping(value = "/downLoad", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public void downLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id) {
		ProjectFile projectFile = projectFileMapper.selectById(Long.valueOf(id));
		try {
			String string = projectFile.getRelativePath();
			String fileName = string.substring(string.indexOf("/") + 1);
			String originalName = projectFile.getOriginalName();

			minIoUtils.download(response, bucketName, fileName, originalName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param request
	 * @param response
	 * @param xftId
	 * @param xiangmuId
	 * @param companyId
	 * @return
	 */
	@PostMapping("/upload")
	public ResultData upload(HttpServletRequest request, MultipartFile image) {
		try {
			request.setCharacterEncoding("utf-8");

			ProjectFile projectFile = projectFileService.saveUpload(request, image);
			return ResultData.success("ok", projectFile);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("error");
		}
	}

	/**
	 * 
	 * @param batchCode
	 * @return
	 */
	@PostMapping("/getRecords")
	public ResultData getRecords(String batchCode) {

		List<ProjectFileDto> list = projectFileMapper.getRecords(batchCode);
		for (ProjectFileDto projectFile : list) {
			User user = iUserService.getById(projectFile.getCreateuserId());
			projectFile.setCreateuserName(user.getNickName());
		}

		return ResultData.success("ok", list);
	}

	/**
	 * 单文件分片上传(存储到本地或服务器)
	 *
	 * @param filePart  单次分片的文件
	 * @param partIndex 当前分片定位
	 * @param partNum   文件分片总数
	 * @param fileName  单次分片的文件名称
	 */
	@PostMapping("/singleFilePartUpload")
	public Result<Boolean> singleFilePartUpload(@RequestParam("filePart") MultipartFile filePart,
			@RequestParam("partIndex") Integer partIndex, @RequestParam("partNum") Integer partNum,
			@RequestParam("fileName") String fileName, @RequestParam("fileUid") String fileUid,
			@RequestParam("fileSize") Long fileSize) {

		log.info("单文件分片上传,总片数:{},分片数:{},文件名:{},大小:{},uid:{}", partNum, partIndex, fileName, filePart.getSize(),
				fileUid);

		Result<Boolean> result = projectFileService.singleFilePartUpload(filePart, partIndex, partNum, fileName,
				fileUid, fileSize);
		return result;
	}

	/**
	 * 
	 * @param _userId
	 * @param request
	 * @param response
	 * @param xftId
	 * @param xiangmuId
	 * @param companyId
	 * @return
	 */
	@PostMapping("/checkUploadFile")
	public ResultData checkUploadFile(@RequestAttribute Long _userId, Long xftId, String originalName) {
		try {

			boolean flag2 = projectFileRecordsService.getTimeComparison(_userId, xftId, originalName);
			if (flag2 != true) {
				return ResultData.error("当前系统中的文档已被其他人更新过，是否仍进行上传？");
			} else {
				return ResultData.success();
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("error");
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param request
	 * @param response
	 * @param xftId
	 * @param xiangmuId
	 * @param companyId
	 * @return
	 */
	@PostMapping("/newUploadFile")
	public ResultData newUploadFile(@RequestAttribute Long _userId, @RequestParam("filePart") MultipartFile filePart,
			@RequestParam("xftId") Long xftId, @RequestParam("xiangmuId") Long xiangmuId,
			@RequestParam("batchCode") String batchCode) {
		try {
			User user = iUserService.getById(_userId);

			ProjectFile projectFile = projectFileService.saveUploadFile(_userId, filePart, xftId, xiangmuId,
					user.getDepartid(), batchCode);
			return ResultData.success("ok", projectFile);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultData.error("error");
		}
	}

	/**
	 * 
	 * @param _userId
	 * @param reqProjectInfo
	 * @return
	 */
	@PostMapping("/newSave")
	public ResultData newSave(@RequestAttribute Long _userId, @RequestBody ProjectFile projectFile) {

		projectFileService.saveNewData(_userId, projectFile);
		return ResultData.success();
	}

	/**
	 * 单文件分片上传(存储到本地或服务器)
	 *
	 * @param filePart  单次分片的文件
	 * @param partIndex 当前分片定位
	 * @param partNum   文件分片总数
	 * @param fileName  单次分片的文件名称
	 */
	@PostMapping("/singleFilePartUpload2")
	public Result<Boolean> singleFilePartUpload2(@RequestParam("filePart") MultipartFile filePart,
			@RequestParam("partIndex") Integer partIndex, @RequestParam("partNum") Integer partNum,
			@RequestParam("fileName") String fileName, @RequestParam("fileUid") String fileUid) {

		log.info("单文件分片上传,总片数:{},分片数:{},文件名:{},大小:{},uid:{}", partNum, partIndex, fileName, filePart.getSize(),
				fileUid);

		Result<Boolean> result = projectFileService.singleFilePartUpload2(filePart, partIndex, partNum, fileName,
				fileUid);
		return result;
	}

}
